﻿using System;
using System.Drawing;
using System.Windows.Forms;

namespace LD.Controls.ControlHelper
{

    /// <summary>
    /// 自动缩放
    /// </summary>
    public class FormScaler
    {
        private static float initialWidth;
        private static float initialHeight;

        /// <summary>
        /// 设定自适应
        /// </summary>
        /// <param name="form">传入的窗体</param>
        /// <param name="isNoHeight">高度不自适应就写true</param>
        public static void ScaleForm(Form form, bool isNoHeight = false)
        {
            if (isNoHeight)
                form.Resize += Form_Resize_NoHight;
            else
                form.Resize += Form_Resize;



            initialWidth = form.Width;
            initialHeight = form.Height;
            SetTag(form);
        }

        private static void SetTag(Control control)
        {
            foreach (Control con in control.Controls)
            {
                con.Tag = $"{con.Width};{con.Height};{con.Left};{con.Top};{con.Font.Size}";
                if (con.Controls.Count > 0)
                {
                    SetTag(con);
                }
            }
        }

        private static void SetControls(float newWidth, float newHeight, Control control)
        {
            foreach (Control con in control.Controls)
            {
                if (con.Tag != null)
                {
                    string[] tagValues = con.Tag.ToString().Split(';');
                    int width = Convert.ToInt32(float.Parse(tagValues[0]) * newWidth);
                    int height = Convert.ToInt32(float.Parse(tagValues[1]) * newHeight);
                    int left = Convert.ToInt32(float.Parse(tagValues[2]) * newWidth);
                    int top = Convert.ToInt32(float.Parse(tagValues[3]) * newHeight);
                    float fontSize = float.Parse(tagValues[4]) * newHeight;
                    con.Width = width;
                    con.Height = height;
                    con.Left = left;
                    con.Top = top;
                    con.Font = new Font(con.Font.Name, fontSize, con.Font.Style, con.Font.Unit);
                    if (con.Controls.Count > 0)
                    {
                        SetControls(newWidth, newHeight, con);
                    }
                }
            }
        }

        private static void Form_Resize(object sender, EventArgs e)
        {
            Form form = (Form)sender;
            float newWidth = form.Width / initialWidth;
            float newHeight = form.Height / initialHeight;
            SetControls(newWidth, newHeight, form);
        }

        private static void Form_Resize_NoHight(object sender, EventArgs e)
        {
            Form form = (Form)sender;
            float newWidth = form.Width / initialWidth;
            float newHeight = 1;//高度写死就行
            SetControls(newWidth, newHeight, form);
        }
    }
}
